package org.appmon.core.agent.loader;

import java.net.URL;
import java.net.URLClassLoader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class LoadUtils {
	
	
	public static final String jarPatternRegex="appmon-core";
	public static final String patternDelimitter = ";";
	public static final String classpath = System.getProperty("java.class.path");
	
	public static String extractJarLocation(){		
		
		
		Pattern patternJarRegex = Pattern.compile(jarPatternRegex);
		Pattern patternDelRegex=Pattern.compile(patternDelimitter);
		Matcher matcherJarRegex = patternJarRegex.matcher(classpath);
		Matcher matcherDelRegex = patternDelRegex.matcher(classpath);
		
		int count = 0;
		int findpoint=0;
		int inpoint=0;
		int outpoint=0;
		int prevbound=0;
		
		while(matcherJarRegex.find()) {
		    count++;
		    findpoint=matcherJarRegex.start();
		}
		if(count>1){
			// log warn message for multiple jar present in class path , take latest as precedence.
		}
		while(matcherDelRegex.find() && count >0) {			
		    if(prevbound<findpoint && matcherDelRegex.end()>findpoint){	
		    	inpoint=prevbound;
		    	outpoint=matcherDelRegex.end()-1;		    	
		    	break;
		    }else{
		    	prevbound=matcherDelRegex.end();
		    }		 
		}		
		if(outpoint==0 && inpoint==0){
			inpoint=prevbound;
			outpoint=classpath.length();
		}				
		return classpath.substring(inpoint, outpoint);		
	}
	
	
	public static String extractJarUrlLocation(){
		
		ClassLoader classloader = Thread.currentThread().getContextClassLoader(); 
		String jarPath="";
		int count=0;
		  
        do {  
            URL[] urls = ((URLClassLoader)classloader).getURLs();
            for(URL url: urls){ 
	           if( url.getFile().contains(jarPatternRegex)){
	            	count++;
	            	jarPath=url.getFile().substring(1,url.getFile().length());
	            }
            }
            classloader = (URLClassLoader)classloader.getParent();  
        } while(classloader != null);
        
        if(count>1){
			// log warn message for multiple jar present in class path , take latest as precedence.
		}else if(count==0){
			//log error no jar found in classpath. Throw runtime exception and stop execution.
		}  
		return jarPath;
	}
	
	

}
